package com.novel.common.job;

import com.novel.common.enums.BeAuthorStatusEnum;
import com.novel.mapper.ApplyAuthorMapper;
import com.novel.pojo.system.ApplyAuthor;
import com.novel.service.ApplyAuthorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * 定时任务：
 * 定时通过用户的成为作者申请
 */
@Slf4j
@Component
public class PassApplyAuthorJob extends QuartzJobBean {

    @Autowired
    private ApplyAuthorMapper applyAuthorMapper;

    @Autowired
    private ApplyAuthorService applyAuthorService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) {

        Properties prop = new Properties();
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();

        try {
            prop.load(new FileInputStream(path + "/manager.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String flag = prop.getProperty("manager.job.pass.apply.author");

        if (!StringUtils.equals(flag, "true")) {
            log.info("定时通过申请Job已关闭");
            return;
        }

        log.info("定时通过申请Job,开始执行");

        Example example = new Example(ApplyAuthor.class);
        example.createCriteria()
                .andEqualTo("status", BeAuthorStatusEnum.WAIT.getCode());
        List<ApplyAuthor> needPassList = applyAuthorMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(needPassList)) {
            return;
        }

        List<String> ids = needPassList.stream().map(ApplyAuthor::getId).collect(Collectors.toList());
        ids.forEach(id -> applyAuthorService.passApplyAuthor(id, "system", "system"));
    }
}